package com.xb.loan.cashier.biz.task.alipay;

import com.xb.loan.cashier.biz.dao.bean.CashierPayChannel;
import com.xb.loan.cashier.biz.pay.alipay.AlipayPayment;
import com.xb.loan.cashier.biz.task.ThirdAccountEncashTask;
import com.xb.loan.cashier.biz.task.bean.ThirdAccountBean;
import com.xb.loan.cashier.biz.task.bean.ThirdAccountEncashBean;
import com.xb.loan.cashier.service.constant.ICashierEnumConst;
import com.xb.loan.util.dom4j.Dom4jHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component(value="alipayWapAccountEncashTask")
@Scope(value="prototype")
public class AlipayWapAccountEncashTask extends ThirdAccountEncashTask {
    
    private static final Logger logger = LoggerFactory.getLogger(AlipayWapAccountEncashTask.class);

    @Override
    protected int getPayChannelType() {
        return ICashierEnumConst.CashierPayChannelType.ALIPAY.getType();
    }
    
    
    @Override
    protected boolean hasThirdAccountTime() {
        return true;
    }

    @Override
    protected Map<String, ThirdAccountBean> getThirdAccountDatas(int pageNo, int pageSize, String day, CashierPayChannel channel) {
        HashMap<String, ThirdAccountBean> result = new HashMap<String, ThirdAccountBean>();
        String signType = ICashierEnumConst.CashierEncryptType.MD5.getDesc();// TODO
        String payChannelId = channel.getPayChannelId();
        String signKey = channel.getMd5Key();
        String partner = channel.getChannelUser();
        String payUrl = channel.getPayUrl();
        String datas;
        try {
            datas = AlipayPayment.account_page_query(pageNo+"", pageSize+"", AlipayPayment.TRANSCODE_TYPE_TX,
                    getStartTime(day), getEndTime(day), partner, signType, signKey, payUrl);
            
            // 验签
            boolean validate = AlipayPayment.account_page_query_validate(datas, signKey, "UTF-8");
            if(!validate){
                logger.error("msg=验签失败 payChannelId="+payChannelId+" day="+day);
                return result;
            }
        } catch (Exception e) {
            logger.error("msg=查询数据失败 payChannelId="+payChannelId+" day="+day, e);
            return result;
        }
        
        List<ThirdAccountBean> list = convert(datas);
        // 数据为空
        if(list==null || list.size()<1){
            logger.info("msg=数据为空 payChannelId="+payChannelId+" day="+day);
            return result;
        }
        for(ThirdAccountBean order : list){
            result.put(order.getOrderId(), order);
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    private List<ThirdAccountBean> convert(String datas) {
        List<ThirdAccountBean> result = new ArrayList<ThirdAccountBean>();
        try {
            Element root = Dom4jHelper.getRootElement(datas);

            Node isSuccess = root.selectSingleNode("/alipay/is_success");
            if(isSuccess==null || !"T".equals(isSuccess.getText())){
                logger.warn("alipay encash account data query fail");
                return result;
            }
            Node access_log = root.selectSingleNode("/alipay/response/account_page_query_result/account_log_list");
            if(access_log==null){
                logger.warn("alipay encash account data is empty");
                return result;
            }
            Node has_next_page = root.selectSingleNode("/alipay/response/account_page_query_result/has_next_page");
            if(has_next_page==null){
                logger.warn("alipay encash account data format error!!");
                return result;
            }
            if("F".equals(has_next_page.getText())){
                hasNextPage = false;
            }
            List<Node> dataList = access_log.selectNodes("/alipay/response/account_page_query_result/account_log_list/AccountQueryAccountLogVO");
            if(dataList==null || dataList.size()<1){
                logger.warn("alipay encash account data is empty");
                return result;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
            for(Node data : dataList){
                ThirdAccountEncashBean order = new ThirdAccountEncashBean();
                Map<String, String> dataMap = Dom4jHelper.childeNodeMapping(data);
                // <AccountQueryAccountLogVO><balance>102247.08</balance><buyer_account>20887120613391810156</buyer_account><currency>156</currency><deposit_bank_no>2015010157326701828</deposit_bank_no><goods_title>购彩充值</goods_title><income>2.00</income><iw_account_log_id>91762492361561</iw_account_log_id><memo> </memo><merchant_out_order_no>24380</merchant_out_order_no><outcome>0.00</outcome><partner_id>2088211249090950</partner_id><rate>0.01</rate><seller_account>20882112490909500156</seller_account><seller_fullname>北京阳光彩通科技有限公司</seller_fullname><service_fee>0.00</service_fee><service_fee_ratio></service_fee_ratio><sign_product_name>快捷手机wap支付</sign_product_name><sub_trans_code_msg>快速支付,支付给个人，支付宝帐户全额</sub_trans_code_msg><total_fee>2.00</total_fee><trade_no>2015010100001000180040307256</trade_no><trade_refund_amount>0.00</trade_refund_amount><trans_code_msg>在线支付</trans_code_msg><trans_date>2015-01-01 00:17:11</trans_date></AccountQueryAccountLogVO>
                // String service_fee = dataMap.get("service_fee");// 交易服务费
                // String trade_refund_amount = dataMap.get("trade_refund_amount");// 累积退款金额
                // String buyer_account = dataMap.get("buyer_account");// 买家支付宝人民币资金账号
                // String seller_account = dataMap.get("seller_account");// 卖家支付宝人民币资金账号
                String merchant_out_order_no = dataMap.get("merchant_out_order_no");// 商户订单号(平台)
                String trans_out_order_no = dataMap.get("trans_out_order_no");// 订单号(第三方)
                String outcome = dataMap.get("outcome");// 交易总金额
                String bank_account_no = dataMap.get("bank_account_no");// 银行账号
                String trans_date = dataMap.get("trans_date");// 交易付款时间（非订单创建时间）。格式为yyyy-MM-dd HH:mm:ss。
                order.setOrderId(merchant_out_order_no);
                order.setOrderIdThird(trans_out_order_no);
                order.setMoney(Double.valueOf(outcome));
                order.setSellAccount(bank_account_no);
                order.setAccountDayThird(sdf1.format(sdf.parse(trans_date)));
                order.setAccountDay(null);
                order.setStatus(ThirdAccountBean.STATUS_SUCCESS);
                result.add(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("msg=convert data fail", e);
        }
        return result;
    }
    
    @Override
    protected boolean compare(ThirdAccountBean dbBean, ThirdAccountBean thirdBean, boolean compareStatas) {
        ThirdAccountEncashBean dbData = (ThirdAccountEncashBean)dbBean;
        ThirdAccountEncashBean thirdData = (ThirdAccountEncashBean)thirdBean;
        if(dbData==null && thirdData==null){
            return true;
        }
        if(dbData==null){
            return false;
        }
        if(thirdData==null){
            return false;
        }
        if(!dbData.getOrderId().equals(thirdData.getOrderId())){
            return false;
        }
        if(dbData.getMoney()!=thirdData.getMoney()){
            return false;
        }
        if(compareStatas){
            if(dbData.getStatus()!=thirdData.getStatus()){
                return false;
            }
        }
        // 支付宝未返回银行卡
//        if(!dbData.getSellAccount().equals(thirdData.getSellAccount())){
//            return false;
//        }
        return true;
    }


}
